﻿namespace HynuIOTA.Web.Areas.Admin.Controllers
{
    using HynuIOTA.Common.Attribute;
    using HynuIOTA.Entity;
    using HynuIOTA.Web.Filters;
    using HynuIOTA.Web.Helpers;
    using HynuIOTA.Web.Models;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using static HynuIOTA.Common.StringConst;

    public class NewsController : BaseController
    {
        /// <summary>
        /// GET: Admin/News/NewsList
        /// 新闻列表页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult NewsList()
        {
            return View();
        }

        /// <summary>
        /// 添加新闻页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddNews()
        {
            return View();
        }

        /// <summary>
        /// 编辑新闻页面
        /// </summary>
        /// <param name="Id">新闻ID</param>
        /// <returns></returns>
        public async Task<ActionResult> EditNews(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsMsg(MODEL_VALIDATE_ERROR);
            }

            var news = await OpContext.Service.News.Where(n => n.Id == Id.Value).FirstOrDefaultAsync();
            if (news == null)
            {
                return OpContext.JsMsg(DATA_NOEXIST_ERROR);
            }

            ViewBag.news = news;
            return View();
        }

        /// <summary>
        /// ANY: Admin/News/GetNewsPage
        /// 新闻列表分页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [AjaxRequest]
        public async Task<ActionResult> GetNewsPage(int page = 1, int rows = int.MaxValue)
        {
            var total = await OpContext.Service.News.Where(n => true).CountAsync();
            var pageList = await OpContext.Service.News.Where(n => true).OrderByDescending(n => n.IsTop).ThenByDescending(n => n.CreateTime).Skip((page - 1)*rows).Take(rows)
                .Select(n => new { n.Id, n.Title, n.Keyword, n.CreateTime, n.IsTop, n.IsMoveImg, n.Click, Channels = n.Channel.Select(c => c.Name), n.User.UserName  }).ToListAsync();

            return OpContext.JsonMsgOK(data: new { total, rows = pageList });
        }

        /// <summary>
        /// POST: Admin/News/PostNews
        /// 添加新闻
        /// </summary>
        /// <param name="newsViewModel"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxRequest]
        public async Task<ActionResult> PostNews(PostNewsViewModel newsViewModel)
        {
            if (ModelState.IsValid == false)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var news = new News()
            {
                Title = newsViewModel.Title,
                Keyword = newsViewModel.Keyword,
                Content = newsViewModel.Content,
                Img = newsViewModel.Img,
                IsTop = newsViewModel.IsTop,
                IsMoveImg = newsViewModel.IsMoveImg,
                CreateTime = DateTime.Now,
                Click = 0,
                UserId = OpContext.UserEntity.Id,
            };
            if (newsViewModel.Channels != null)
            {
                var channels = await OpContext.Service.Channel.Where(c => newsViewModel.Channels.Contains(c.Id))
                    .ToListAsync();
                foreach (var item in channels)
                {
                    news.Channel.Add(item);
                }
            }

            OpContext.Service.News.Add(news);

            var result = await OpContext.SaveChangesAsync();
            if (result != null)
            {
                return result;
            }
            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.News);
            return OpContext.JsonMsgOK(DATA_ADD_SUCCESS);
        }

        /// <summary>
        /// DELETE: Admin/News/DeleteNews
        /// 删除新闻
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult> DeleteNews(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var news = await OpContext.Service.News.Where(n => n.Id == Id.Value).FirstOrDefaultAsync();
            if (news == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            OpContext.Service.News.Delete(news);
            var result = await OpContext.SaveChangesAsync();

            if (result != null)
            {
                return result;
            }

            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.News);
            return OpContext.JsonMsgOK(DATA_DELECT_SUCCESS);
        }

        [HttpPut]
        public async Task<ActionResult> PutNews(PutNewsViewModel newsViewModel)
        {
            if (ModelState.IsValid == false)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var news = await OpContext.Service.News.Where(n => n.Id == newsViewModel.Id).Include(n => n.Channel).FirstOrDefaultAsync();
            if (news == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            Tools.SetValues(news,newsViewModel,ModelState.Keys.ToArray());
            news.Channel.Clear();
            if (newsViewModel.Channels != null)
            {
                var channels = await OpContext.Service.Channel.Where(c => newsViewModel.Channels.Contains(c.Id))
                    .ToListAsync();
                channels.ForEach(c => news.Channel.Add(c));
            }

            var result = await OpContext.SaveChangesAsync();
            if (result != null)
            {
                return result;
            }
            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.News);

            return OpContext.JsonMsgOK(DATA_MODIFY_SUCCESS);
        }
    }
}